<template>
  <div>
    <el-drawer v-model="drawer" title="上传Excel文件" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-alert type="success" :closable="false">
          <template #default>
            <div v-html="recentInfo.replace(/\n/g, '<br>')"></div>
          </template>
        </el-alert>
        <br />
        <el-form-item label="文件名：" prop="fileName">
          <el-input v-model="ruleForm.fileName" placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="ruleForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="文件：">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            action="#"
            accept=".xlsx"
            :auto-upload="false"
            :on-change="beforeUpload"
            v-model:file-list="fileList"
            style="width: 280px"
          >
            <template #trigger>
              <el-button type="primary" icon="Upload" :disabled="fileList.length === 1">
                上传文件
              </el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { postExcelUpload } from '@/api/controller/excel-controller/index'
  import { getUploadRecordGetRecentInfo } from '@/api/controller/upload-record-controller/index'
  const drawer = ref(false)
  const recentInfo = ref('')
  const fileList = ref([])
  const show = async () => {
    await getUploadRecordGetRecentInfo().then((res) => {
      recentInfo.value = res.data
    })
    ruleForm.value = {
      fileName: null,
      remark: null,
    }
    fileList.value = []
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    fileName: null,
    remark: null,
  })
  const rules = reactive({
    fileName: [
      { required: true, message: '请输入文件名', trigger: 'blur' },
      { min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' },
    ],
    remark: [{ min: 0, max: 64, message: '长度不超过64个字符', trigger: 'blur' }],
  })
  const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
      if (valid) {
        if (fileList.value[0]) {
          const file = new FormData()
          file.append('file', fileList.value[0].raw)
          ElMessage.warning('正在上传，上传需要半分钟到一分钟，请耐心等待')
          const result = await postExcelUpload(ruleForm.value, file, { loading: true, text: true })
          ElMessage.success('上传成功')
          let b = new Blob([result]) //拿到文件流下载对象
          let url = window.URL.createObjectURL(b) //生成文件流下载链接
          let a = document.createElement('a') //创建一个a标签用来跳转
          a.href = url // a标签 href  赋值 链接
          a.download = '上传结果.txt' //设置下载文件的文件名和文件格式
          document.body.appendChild(a) //将标签DOM，放置页面
          a.click()
          window.URL.revokeObjectURL(url) //释放 url 对象内存
          document.body.removeChild(a) //移除标签节点
          await emit('getData')
          drawer.value = false
        } else {
          ElMessage.warning('请上传文件')
          return false
        }
      } else {
        ElMessage.warning('请正确填写表单')
        return false
      }
    })
  }
  const beforeUpload = (file) => {
    const { name } = file
    //   文件类型限制
    const fileTypeFlag = /^.xlsx$/.test(name.substring(name.lastIndexOf('.')).toLowerCase())
    if (!fileTypeFlag) {
      ElMessage.warning('文件类型只能是.xlsx')
      fileList.value = []
      return false
    }
    if (!ruleForm.value.fileName) {
      ruleForm.value.fileName = name.substring(0, name.lastIndexOf('.'))
    }
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
